package com.thlws.rabbitmq.routing;

import com.rabbitmq.client.*;

/***
 * 路由模式
 * BuiltinExchangeType.DIRECT
 * 本质是是消费端Consumer对 routingKey 的过滤，消费端可以绑定多个routingKey。
 *
 */
public class Consumer {
	
	private static final String EXCHANGE_NAME = "direct_logs";

	public static void main(String[] args) throws Exception {
		
		ConnectionFactory factory = new ConnectionFactory();
		factory.setHost("116.228.212.36");
		factory.setUsername("hanley");
		factory.setPassword("hanley");
		factory.setVirtualHost("/test");
		
	    Connection connection = factory.newConnection();
	    Channel channel = connection.createChannel();

	    channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.DIRECT);
	    String queueName = channel.queueDeclare().getQueue();
	    
	    //Consumer 绑定多个routingKey
	    String routingKey = "info";
	    String routingKeyError = "error";
	    channel.queueBind(queueName, EXCHANGE_NAME, routingKey);
	    channel.queueBind(queueName, EXCHANGE_NAME, routingKeyError);

	    //接收消息
	    DeliverCallback deliverCallback = (consumerTag, delivery) -> {
	        String message = new String(delivery.getBody(), "UTF-8");
	        System.out.println(" [x] Received '" +
	            delivery.getEnvelope().getRoutingKey() + "':'" + message + "'");
	    };
	    channel.basicConsume(queueName, true, deliverCallback, consumerTag -> { });

	}

}
